package com.eims.sls_app.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import bls.juejin.cn.R;

import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.AccountDetails;
import com.eims.sls_app.dataaccess.LotteryContent;
import com.eims.sls_app.dataaccess.Schemes;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.ui.AllAccountBetLottery.MyAsynTask;
import com.eims.sls_app.ui.AllAccountBetLottery.MyHandler;
import com.eims.sls_app.ui.AllAccountBetLottery.MyItemCLickListener;
import com.eims.sls_app.ui.adapter.AccountDeatialAdapter;
import com.eims.sls_app.ui.adapter.CenterAccountLotteryAdapter;
import com.eims.sls_app.ui.adapter.CenterLotteryAdapter;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.utils.NetWork;
import com.eims.sls_app.view.MyToast;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 账户明细提现模块
 * 
 * @author zht
 * 
 */

public class JoinAccountBetLottery implements OnScrollListener {

	private View view;
	private PullToRefreshListView all_listView;
	private CenterAccountLotteryAdapter adapter;
	private Context context;
	private TextView tv_title;

	private MyHandler myHandler;
	private MyAsynTask myAsynTask;

	private List<List<Schemes>> listAllSchemes = new ArrayList<List<Schemes>>();
	private List<String> list = new ArrayList<String>();

	private String opt, auth, info, time, imei, crc, key; // 格式化后的参数

	private int size = 30;
	private int pageIndex = 1; // 页码
	// private int pageSize = size; // 每页显示行数
	private int sort = 5; // 排序方式
	private int isPurchasing = 3; // 返回类型
	private int pageSize = 20;
	/** 要更改的 **/
	private LinearLayout ll;
	private ProgressBar pb;
	private int isEnd = 0;

	// 最后可见条目的索引
	private int lastVisibleIndex;

	// 新增参数
	private int searchCondition = 4;

	public int year;
	public int month;
	public int day;

	// private List<LotteryContent> contents = new ArrayList<LotteryContent>();

	private AccountDeatialAdapter deatialAdapter;

	private final List<AccountDetails> mAccountData = new ArrayList<AccountDetails>();

	public JoinAccountBetLottery(Context context, View v) {
		this.view = v;
		this.context = context;
		myHandler = new MyHandler();
		time = RspBodyBaseBean.getTime();
		imei = RspBodyBaseBean.getIMEI(context);
		// key = MD5.md5(App.user.getUserPass() + App.MD5_key);
		key = App.key;
	}

	public JoinAccountBetLottery(Context context, View v, int year, int month,
			int day) {
		this.view = v;
		this.context = context;
		myHandler = new MyHandler();
		time = RspBodyBaseBean.getTime();
		imei = RspBodyBaseBean.getIMEI(context);
		// key = MD5.md5(App.user.getUserPass() + App.MD5_key);
		key = App.key;
		this.year = year;
		this.month = month;
		this.day = day;
	}

	public void init() {
		all_listView = (PullToRefreshListView) view
				.findViewById(R.id.ptr_MyAccount);
		all_listView.setMode(Mode.BOTH);
		tv_title = (TextView) view.findViewById(R.id.tv_title);
		tv_title.setText("正在加载中..");
		tv_title.setVisibility(View.VISIBLE);
		// Calendar now = Calendar.getInstance();
		// year = now.get(Calendar.YEAR);
		// month = now.get(Calendar.MONTH) + 1;
		// day = App.getLastDay(year, month);

		/** 要更改的 新加的加载图片 **/

		myAsynTask = new MyAsynTask();
		myAsynTask.execute();

		all_listView
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {

						// 下拉刷新
						all_listView
								.getLoadingLayoutProxy(true, false)
								.setLastUpdatedLabel(
										"最近更新: "
												+ LotteryUtils
														.Long2DateStr_detail(System
																.currentTimeMillis()));
						if (NetWork.isConnect(context)) {

							if (myAsynTask != null) {
								myAsynTask.cancel(true);
							}
							mAccountData.clear();
							pageIndex = 1;
							myAsynTask = new MyAsynTask();
							myAsynTask.execute();
						} else {
							MyToast.getToast(context, "网络连接异常，请检查网络").show();
							all_listView.onRefreshComplete();
						}

					}

					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {

						// 上拉加载

						if (NetWork.isConnect(context)) {

							if (myAsynTask != null) {
								myAsynTask.cancel(true);
							}
							pageIndex++;
							myAsynTask = new MyAsynTask();
							myAsynTask.execute();
						} else {
							MyToast.getToast(context, "网络连接异常，请检查网络").show();
							all_listView.onRefreshComplete();
						}

					}

				});

	}

	/** 异步任务 */
	class MyAsynTask extends AsyncTask<Void, Integer, String> {

		/** 在后台执行的程序 */
		@Override
		protected String doInBackground(Void... params) {
			int p;

			info = RspBodyBaseBean.changeFundsInfo_info(searchCondition,
					pageIndex, pageSize, "0", year + "-" + month
							+ "-1 00:00:00", year + "-" + month + "-" + day
							+ " 23:59:59");

			// Log.i("x", "获得我全部投注记录    info  " + info);

			opt = "44";
			crc = RspBodyBaseBean.getCrc(time, imei, key, info,
					App.user.getUid());
			auth = RspBodyBaseBean.getAuth(crc, time, imei,
					App.user.getUid());
			String[] values = { opt, auth, info };
			String result = HttpUtils.doPost(App.names, values,
					App.path);
			Log.i("xxxx  opt提款", ""+RequestParams.convertParams(context, opt, info));
			 Log.i("x", "得到全部内容   " + result);

			try {
				JSONObject jsonObject = new JSONObject(result);

				if (jsonObject != null) {
					JSONArray array = jsonObject
							.getJSONArray("dtAccountDetails");
					if (array.length() > 0) {
						for (int i = 0; i < array.length(); i++) {

							JSONObject obj = array.getJSONObject(i);
							AccountDetails ad = new AccountDetails();
							ad.date = obj.optString("date");
							JSONArray jsonArray = obj
									.getJSONArray("dateDetail");
							List<Schemes> listData = new ArrayList<Schemes>();

							if (jsonArray.length() > 0) {
								for (int j = 0; j < jsonArray.length(); j++) {
									JSONObject object = jsonArray
											.getJSONObject(j);
									JSONArray array2 = object
											.getJSONArray("buyContent");
									Schemes schemes = new Schemes();

									schemes.setId(object.optString("id"));
									schemes.setSchemeNumber(object
											.optString("schemeNumber"));
									schemes.setAssureMoney(object
											.optDouble("assureMoney"));
									schemes.setAssureShare(object
											.optInt("assureShare"));
									schemes.setBuyed(object.optString("buyed"));
									schemes.setInitiateName(LotteryUtils
											.addRexStar(object
													.optString("initiateName")));
									schemes.setInitiateUserID(object
											.optString("initiateUserID"));
									schemes.setIsPurchasing(object
											.optString("isPurchasing"));
									schemes.setIsChase(object.optInt("isChase"));
									schemes.setAssureMoney(object
											.optDouble("assureMoney"));
									schemes.setWinMoney(object
											.optDouble("winMoney"));
									schemes.setWinNumber(object
											.optString("winNumber"));

									schemes.setTitle(object.optString("title"));

									schemes.setShare(object.optInt("share"));

									schemes.setSecrecyLevel(object
											.optInt("secrecyLevel"));

									schemes.setSchemeNumber(object
											.optString("schemeNumber"));
									schemes.setSchedule(object
											.optInt("schedule"));
									schemes.setQuashStatus(object
											.optInt("quashStatus"));
									schemes.setMyBuyShare(object
											.optInt("myBuyShare"));
									schemes.setMyBuyMoney(object
											.optString("myBuyMoney"));
									schemes.setLevel(object.optInt("level"));
									schemes.setMultiple(object
											.optInt("multiple"));

									schemes.setLotteryID(object
											.optString("lotteryID"));
									schemes.setOrderTitle(object
											.optString("orderTitle"));
									schemes.setDescription(object
											.optString("description"));
									schemes.setType(object.optInt("type"));
									schemes.setDateTime(object
											.optString("datetime"));

									schemes.setMoney(object.optDouble("money"));
									String optString2 = object
											.optString("handselMoney");
									if ("".equals(optString2)) {
										optString2 = "0";
									}
									double handselMoney = Double
											.parseDouble(optString2);
									schemes.setHandselMoney(handselMoney);
									// schemes.setHandselMoney(object
									// .optDouble("handselMoney"));
									schemes.setId(object.optString("id"));
									schemes.setBuyed(object.optString("buyed"));

									// Log.i("detailMoney---join account",
									// object.optDouble("detailMoney")+"");
									// schemes.setDetailMoney(object
									// .optDouble("detailMoney"));
									String optString = object
											.optString("detailMoney");
									if ("".equals(optString)) {
										optString = "0";
									}
									double detailMoney = Double
											.parseDouble(optString);
									schemes.setDetailMoney(detailMoney);

									schemes.setIsOpened(object
											.optString("isOpened"));

									schemes.setLotteryName(object
											.optString("lotteryName"));
									schemes.setWinMoneyNoWithTax(object
											.optDouble("winMoneyNoWithTax"));
									schemes.setSumSchemeMoney(object
											.optDouble("sumSchemeMoney"));

									schemes.setInitiateUserID(object
											.optString("initiateUserID"));
									schemes.setInitiateName(object
											.optString("initiateName"));

									schemes.setFromClient(object
											.optInt("fromClient"));

									schemes.setIsPurchasing(object
											.optString("isPurchasing"));

									schemes.setIsuseID(object
											.optString("isuseID"));
									// "buyedShare": "9",

									schemes.setIsuseName(object
											.optString("isuseName"));
									schemes.setRecordCount(object
											.optInt("recordCount"));
									schemes.setSchemeStatus(object
											.optString("schemeStatus"));
									schemes.setAssureShare(object
											.optInt("assureShare"));
									schemes.setSerialNumber(object
											.optInt("serialNumber"));

									schemes.setShareMoney(object
											.optInt("shareMoney"));
									schemes.setoType(object.optString("oType"));
									schemes.setSurplusShare(object
											.optInt("surplusShare"));
									schemes.setOrderTime(object
											.optString("orderTime"));
									schemes.setWinDescription(object
											.getString("WinDescription"));
									List<LotteryContent> contents = new ArrayList<LotteryContent>();
									for (int m = 0; m < array2.length(); m++) {

										try {

											Object obj1 = array2.get(m);
											if (obj1 instanceof JSONArray) {

												JSONArray array3 = (JSONArray) obj1;
												for (int k = 0; k < array3
														.length(); k++) {
													JSONObject jsonObject2 = array3
															.getJSONObject(k);
													LotteryContent content = new LotteryContent();
													content.setPlayType(jsonObject2
															.optString("playType"));
													content.setSumMoney(jsonObject2
															.optString("sumMoney"));
													content.setSumNum(jsonObject2
															.optString("sumNum"));
													content.setLotteryNumber(jsonObject2
															.optString("lotteryNumber"));
													contents.add(content);

												}

											} else {

												JSONObject obj2 = (JSONObject) obj1;
												LotteryContent content = new LotteryContent();
												content.setPlayType(obj2
														.optString("playType"));
												content.setSumMoney(obj2
														.optString("sumMoney"));
												content.setSumNum(obj2
														.optString("sumNum"));
												content.setLotteryNumber(obj2
														.optString("lotteryNumber"));
												contents.add(content);

											}

										} catch (Exception e) {
											e.printStackTrace();
										}

									}

									schemes.setBuyContent(contents);

									// "joinUserID": "0",

									// "shareMoney": "1.2",

									listData.add(schemes);
								}

								Log.d("haitao", "size " + listData.size());
							}

							ad.dateDetail = listData;

							mAccountData.add(ad);
						}

					}

				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// handler.sendEmptyMessage(0);

			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			// if (null == result)
			// return;
			// if ("1".equals(result)) {
			// myHandler.sendEmptyMessage(-1);
			// }
			//
			// myHandler.sendEmptyMessage(Integer.parseInt(result));

			// AccountDeatialAdapter adapter = new
			// AccountDeatialAdapter(context, mAccountData);
			tv_title.setVisibility(View.GONE);
			deatialAdapter = new AccountDeatialAdapter(context, mAccountData);
			all_listView.setAdapter(deatialAdapter);
			all_listView.onRefreshComplete();
			super.onPostExecute(result);
		}
	}

	/** 进行页面刷新 */
	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// case 0:
			// //getThreeMonth();
			// // adapter.setDate(list, listAllSchemes);
			// adapter.notifyDataSetChanged();
			// all_listView.setOnScrollListener(AllAccountBetLottery.this);
			// System.out.println("getTotalCount111" + getTotalCount());
			// if (getTotalCount() % 30 != 0) {
			// myHandler.sendEmptyMessage(-1);
			// }
			// if (!LotteryUtils.checkThreeMonth(list)) {
			// myHandler.sendEmptyMessage(-1);
			// }
			// break;
			// case -1:
			// all_listView.removeFooterView(ll);
			// all_listView.setOnScrollListener(null);
			// break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}

	private void getThreeMonth() {
		String now = LotteryUtils.getSchemeTime(System.currentTimeMillis());
		for (int i = 0; i < list.size(); i++) {
			if (!LotteryUtils.compareMonth(now, list.get(i))) {
				list.remove(i);
				listAllSchemes.remove(i);
			}
		}
	}

	class MyItemCLickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {
			TextView tv_id = (TextView) view.findViewById(R.id.tv_id);

			int itemId = Integer.parseInt(tv_id.getText().toString());

			Schemes scheme = listAllSchemes.get(itemId).get(position);

			Intent intent = null;

			System.out.println(111);

			if (scheme.getIsChase() == 0)
				if ("72".equals(scheme.getLotteryID())
						|| "73".equals(scheme.getLotteryID()))
					intent = new Intent(context, MyCommonLotteryInfo_jc.class);
				else
					intent = new Intent(context, MyCommonLotteryInfo.class);
			else
				intent = new Intent(context, MyFollowLotteryInfo.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			App.scheme=scheme;
			intent.putExtra("scheme", scheme);
			context.startActivity(intent);
		}
	}

	private int getTotalCount() {
		int total = 0;

		for (List<Schemes> list : listAllSchemes) {
			total += list.size();
			System.out.println(" list.size()" + list.size());
		}
		System.out.println("-+---+--+-" + total);

		return total;

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& lastVisibleIndex == adapter.getCount()) {
			if (isEnd != getTotalCount()) {
				pageIndex++;
				isEnd = getTotalCount();
				myAsynTask = new MyAsynTask();
				myAsynTask.execute();
			} else

			{
				myHandler.sendEmptyMessage(-1);
			}
		}
	}

	public void Refresh(int year, int month, int day) {
		if (null != myAsynTask) {
			this.year = year;
			this.month = month;
			this.day = day;
			this.pageIndex = 1;
			// if (all_listView.getFooterViewsCount() == 0) {
			// all_listView.addFooterView(ll);
			// }
			myAsynTask.cancel(true);
			mAccountData.clear();
			deatialAdapter.notifyDataSetChanged();
			myAsynTask = new MyAsynTask();
			myAsynTask.execute();
		}
		// Toast.makeText(context, "year="+year, Toast.LENGTH_SHORT).show();
	}

}
